<template>
  <div class="app-container">
    <!-- 搜索区 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="设备名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入设备名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="在线状态" prop="onlineStatus">
        <el-select v-model="queryParams.onlineStatus" placeholder="请选择状态" clearable>
          <el-option v-for="dict in onlineStatusOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮行 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5"><el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['iot:device:add']">新增</el-button></el-col>
      <el-col :span="1.5"><el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single"
          @click="handleUpdate" v-hasPermi="['iot:device:edit']">修改</el-button></el-col>
      <el-col :span="1.5"><el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple"
          @click="handleDelete" v-hasPermi="['iot:device:remove']">删除</el-button></el-col>
      <el-col :span="1.5"><el-button type="success" plain icon="el-icon-open" size="mini" :disabled="multiple"
          @click="handleTurnOn">批量开灯</el-button></el-col>
      <el-col :span="1.5"><el-button type="danger" plain icon="el-icon-turn-off" size="mini" :disabled="multiple"
          @click="handleTurnOff">批量关灯</el-button></el-col>
      <el-col :span="3">
        <div class="batch-control-item">
          <span class="label">亮度调节</span>
          <el-select v-model="batchBrightness" :disabled="multiple" placeholder="亮度" size="mini" style="width: 100px;"
            @change="handleSetBrightness">
            <el-option v-for="item in brightnessOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </div>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getListForTable"></right-toolbar>
    </el-row>

    <!-- 主体内容区：左右分栏 -->
    <el-row :gutter="20" class="main-content">
      <!-- 左侧：数据表格和分页 -->
      <el-col :span="14" class="table-container">
        <el-table ref="table" v-loading="loading" :data="deviceList" @selection-change="handleSelectionChange"
          @row-click="handleRowClick" highlight-current-row height="100%">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="设备名称" align="center" prop="name" :show-overflow-tooltip="true" />
          <el-table-column label="在线状态" align="center" prop="onlineStatus">
            <template slot-scope="scope"><el-tag
                :type="scope.row.onlineStatus === 1 ? 'success' : 'info'">{{ scope.row.onlineStatus === 1 ? '在线' : '离线' }}</el-tag></template>
          </el-table-column>
          <el-table-column label="工作状态" align="center" prop="status">
            <template slot-scope="scope"><el-tag
                :type="scope.row.status === 1 ? 'success' : 'danger'">{{ scope.row.status === 1 ? '开' : '关' }}</el-tag></template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="120">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-edit" @click.stop="handleUpdate(scope.row)"
                v-hasPermi="['iot:device:edit']">修改</el-button>
              <el-button size="mini" type="text" icon="el-icon-delete" @click.stop="handleDelete(scope.row)"
                v-hasPermi="['iot:device:remove']">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
          @pagination="getListForTable" />
      </el-col>

      <!-- 右侧：地图容器 -->
      <el-col :span="10">
        <div id="map-container" class="map-box" v-loading="mapLoading" element-loading-text="地图加载中..."></div>
      </el-col>
    </el-row>

    <!-- 添加或修改设备对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body @close="clearMapSelection">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12"><el-form-item label="设备名称" prop="name"><el-input v-model="form.name"
                placeholder="请输入设备名称" /></el-form-item></el-col>
          <el-col :span="12"><el-form-item label="设备ID" prop="deviceId"><el-input v-model="form.deviceId"
                placeholder="请输入设备ID" /></el-form-item></el-col>
        </el-row>
        <el-row>
          <el-col :span="12"><el-form-item label="设备型号" prop="model"><el-input v-model="form.model"
                placeholder="请输入设备型号" /></el-form-item></el-col>
          <el-col :span="12"><el-form-item label="设备IP" prop="deviceIp"><el-input v-model="form.deviceIp"
                placeholder="请输入设备IP" /></el-form-item></el-col>
        </el-row>
        <el-form-item label="设备地址" prop="deviceAddress"><el-input v-model="form.deviceAddress"
            placeholder="请输入设备地址" /></el-form-item>
        <el-form-item label="关联页面标题" prop="titleConfigId">
          <el-select v-model="form.titleConfigId" placeholder="请选择页面标题" clearable style="width: 100%;">
            <el-option v-for="title in titleOptions" :key="title.id" :label="title.titleCn" :value="title.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    listDevice,
    getDevice,
    delDevice,
    addDevice,
    updateDevice,
    getMapList,
    turnOn,
    turnOff,
    setBrightness
  } from "@/api/iot/trail";
  import AMapLoader from "@amap/amap-jsapi-loader";

  export default {
    name: "DeviceListWithMap",
    data() {
      return {
        // 页面加载状态
        loading: true,
        mapLoading: true,
        // 表格选择相关
        ids: [],
        single: true,
        multiple: true,
        // UI控制
        showSearch: true,
        title: "",
        open: false,
        // 表格和分页
        total: 0,
        deviceList: [],
        // 搜索和表单选项
        onlineStatusOptions: [{
            label: "在线",
            value: 1
          },
          {
            label: "离线",
            value: 0
          }
        ],
        titleOptions: [],
        batchBrightness: null,
        brightnessOptions: [{
            label: '0%',
            value: 0
          }, {
            label: '10%',
            value: 10
          }, {
            label: '20%',
            value: 20
          },
          {
            label: '30%',
            value: 30
          }, {
            label: '40%',
            value: 40
          }, {
            label: '50%',
            value: 50
          },
          {
            label: '60%',
            value: 60
          }, {
            label: '70%',
            value: 70
          }, {
            label: '80%',
            value: 80
          },
          {
            label: '90%',
            value: 90
          }, {
            label: '100%',
            value: 100
          },
        ],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          name: null,
          onlineStatus: null,
        },
        // 地图相关
        map: null,
        markers: [],
        activeMarker: null,
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          name: [{
            required: true,
            message: "设备名称不能为空",
            trigger: "blur"
          }],
          deviceId: [{
            required: true,
            message: "设备ID不能为空",
            trigger: "blur"
          }],
        },
      };
    },
    mounted() {
      this.initAMap();
    },
    beforeDestroy() {
      this.map?.destroy();
    },
    created() {
      this.getListForTable();
    },
    methods: {
      /** 初始化地图 */
      initAMap() {
        window._AMapSecurityConfig = {
          securityJsCode: "0d81e09a17f2c4c7d64b72815085f1d3",
        };
        AMapLoader.load({
            key: "ead15e1a0966ba127d1202c9353ad124",
            version: "2.0",
            plugins: ["AMap.ToolBar",
              "AMap.Scale",
              "AMap.Marker",
              "AMap.Icon",
              "AMap.Size"
            ],
          })
          .then((AMap) => {
            this.map = new AMap.Map("map-container", {
              // 设置地图容器id
              viewMode: "2D", // 是否为3D地图模式
              zoom: 5, // 初始化地图级别
              center: [108.94, 34.26], // 初始化地图中心点位置
            });
            this.map.addControl(new AMap.ToolBar());
            this.map.addControl(new AMap.Scale());
            this.getListForMap();
          })
          .catch((e) => {
            console.log(e);
          });
      },

      /** 加载地图上的所有点位 */
      getListForMap(AMap) {
        if (!this.map) return;

        listLocations({
          pageNum: 1,
          pageSize: 9999
        }).then(response => {
          this.updateMapMarkers(response.rows);
        });
      },

      /** 加载表格中的分页数据 */
      getListForTable() {
        this.loading = true;
        listDevice(this.queryParams).then(response => {
          this.deviceList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },

      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getListForTable();
        if (window.AMap) this.getListForMap(window.AMap);
      },

      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },

      /** 更新地图标记点 */
      updateMapMarkers(devices, AMap) {
        if (!this.map || !AMap) {
          console.error("更新点位失败：地图实例或AMap对象未准备好。");
          return;
        }

        // 清除旧的点位
        this.map.remove(this.markers);
        this.markers = [];

        // 增加日志：查看原始数据
        console.log("从API获取到的原始设备数据:", devices);

        if (!devices || !Array.isArray(devices)) {
          console.warn("设备数据为空或格式不正确，无法渲染点位。");
          return;
        }

        const validDevices = devices.filter(dev => dev.longitude && dev.latitude);

        // 增加日志：查看过滤后的有效数据
        console.log("过滤后有效的设备数据:", validDevices);

        if (validDevices.length === 0) {
          console.warn("没有找到包含有效经纬度的设备。");
          return;
        }

        validDevices.forEach(dev => {
          const marker = new AMap.Marker({
            position: [dev.longitude, dev.latitude],
            title: dev.name,
            extData: {
              id: dev.id
            }
          });
          marker.on('click', () => {
            this.handleMarkerClick(dev, AMap);
          });
          this.markers.push(marker);
        });

        // 增加日志：查看创建的 Marker 数量
        console.log(`创建了 ${this.markers.length} 个 Marker。`);

        this.map.add(this.markers);

        // 增加日志：确认 setFitView 被调用
        console.log("调用 map.setFitView() 自动缩放视野。");
        this.map.setFitView();
      },

      /** 高亮 Marker 的辅助方法 */
      highlightMarker(deviceId, AMap) {
        if (this.activeMarker) this.activeMarker.setIcon();
        const targetMarker = this.markers.find(m => m.getExtData().id === deviceId);
        if (targetMarker) {
          targetMarker.setIcon(new AMap.Icon({
            image: '//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-red.png',
            size: new AMap.Size(25, 34),
            imageSize: new AMap.Size(25, 34)
          }));
          targetMarker.setTop(true);
          this.activeMarker = targetMarker;
        }
      },

      /** 联动一：点击表格行，地图高亮 */
      handleRowClick(row) {
        if (row.longitude && row.latitude) {
          this.map.setZoomAndCenter(15, [row.longitude, row.latitude]);
          this.highlightMarker(row.id, window.AMap);
        }
      },

      /** 联动二：点击地图标记，表格高亮 */
      handleMarkerClick(deviceData, AMap) {
        const targetRow = this.deviceList.find(row => row.id === deviceData.id);
        if (targetRow) {
          this.$refs.table.setCurrentRow(targetRow);
        } else {
          this.$modal.msgInfo("该设备不在当前表格页面");
        }
        this.highlightMarker(deviceData.id, AMap);
      },

      /** 关闭弹窗时清除高亮 */
      clearMapSelection() {
        if (this.activeMarker) {
          this.activeMarker.setIcon();
          this.activeMarker = null;
        }
      },

      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },

      // 表单重置
      reset() {
        this.form = {
          id: null,
          deviceId: null,
          name: null,
          model: null,
          deviceIp: null,
          deviceAddress: null,
          titleConfigId: null
        };
        this.titleOptions = [];
        this.resetForm("form");
      },

      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id);
        this.single = selection.length !== 1;
        this.multiple = !selection.length;
      },

      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        getDevice(0).then(response => {
          this.titleOptions = response.titleOptions || [];
          this.open = true;
          this.title = "添加设备";
        });
      },

      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids[0];
        getDevice(id).then(response => {
          if (response && response.data) {
            this.form = response.data.data;
            this.titleOptions = response.data.titleOptions || [];
            this.open = true;
            this.title = "修改设备";
          }
        });
      },

      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            const request = this.form.id != null ? updateDevice(this.form) : addDevice(this.form);
            request.then(() => {
              this.$modal.msgSuccess(this.form.id != null ? "修改成功" : "新增成功");
              this.open = false;
              this.getListForTable();
              if (window.AMap) this.getListForMap(window.AMap);
            });
          }
        });
      },

      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$modal.confirm('是否确认删除设备编号为"' + ids + '"的数据项？').then(() => delDevice(ids))
          .then(() => {
            this.getListForTable();
            if (window.AMap) this.getListForMap(window.AMap);
            this.$modal.msgSuccess("删除成功");
          });
      },

      /** 导出按钮操作 */
      handleExport() {
        this.download('iot/device/export', {
          ...this.queryParams
        }, `device_${new Date().getTime()}.xlsx`);
      },

      /** 批量开灯操作 */
      handleTurnOn() {
        if (this.multiple) return;
        this.$modal.confirm('是否确认开启选中的' + this.ids.length + '个设备？').then(() => turnOn(this.ids))
          .then(() => {
            this.$modal.msgSuccess("开启指令已发送");
            setTimeout(() => this.getListForTable(), 3000);
          });
      },

      /** 批量关灯操作 */
      handleTurnOff() {
        if (this.multiple) return;
        this.$modal.confirm('是否确认关闭选中的' + this.ids.length + '个设备？').then(() => turnOff(this.ids))
          .then(() => {
            this.$modal.msgSuccess("关闭指令已发送");
            setTimeout(() => this.getListForTable(), 3000);
          });
      },

      /** 批量亮度调节 */
      handleSetBrightness(brightness) {
        if (this.multiple) return;
        setBrightness({
          ids: this.ids,
          brightness: brightness
        }).then(() => {
          this.$modal.msgSuccess("亮度调节指令已发送");
          setTimeout(() => this.getListForTable(), 3000);
        }).finally(() => {
          this.batchBrightness = null;
        });
      }
    }
  };
</script>

<style lang="scss" scoped>
  /* 从您的成功案例中复制全套的 flex 布局样式 */
  .app-container {
    display: flex;
    flex-direction: column;
    height: calc(100vh - 84px);
    padding: 0;
  }

  .el-form,
  .mb8 {
    padding: 18px 20px 0;
    flex-shrink: 0;
  }

  .main-content {
    flex-grow: 1;
    min-height: 0;
    padding: 10px 20px 20px;
    display: flex;
  }

  .main-content>.el-col {
    display: flex;
    flex-direction: column;
    height: 100%;
  }

  .table-container {
    display: flex;
    flex-direction: column;
    height: 100%;

    .el-table {
      width: 100%;
      flex-grow: 1;
      min-height: 0;
    }

    .pagination-container {
      flex-shrink: 0;
    }
  }

  .map-box {
    width: 100%;
    height: 100%;
    border: 1px solid #e2e2e2;
    border-radius: 4px;
  }

  .batch-control-item {
    display: flex;
    align-items: center;
    font-size: 14px;

    .label {
      margin-right: 10px;
    }
  }
</style>
